<template>
  <j-modal
    :title="title"
    :visible="visible"
    @cancel="handleCancel"
    @ok="handleOk"
    width="780px"
    :confirmLoading="confirmLoading"
    :okText="$t('保存')"
    :cancelText="$t('关闭')"
    v-drag
  >
    <div>
      <a-form-model
        :rules="rules"
        :model="dataForm"
        ref="form"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        v-enterToNext
      >
        <a-form-model-item prop="appid" ref="appid" label="APPID:">
          <a-input v-model="dataForm.appid"></a-input>
        </a-form-model-item>
        <a-form-model-item prop="merchants" ref="merchants" :label="$t('商户号')">
          <a-input v-model="dataForm.merchants"></a-input>
        </a-form-model-item>
        <a-form-model-item prop="apikey" ref="apikey" label="ApiKey:">
          <a-input v-model="dataForm.apikey"></a-input>
        </a-form-model-item>
        <a-form-model-item style="margin-bottom: 0px" prop="payValidity" ref="payValidity" :label="$t('支付有效期')">
          <a-input :suffix="$t('分钟')" v-model="dataForm.payValidity"></a-input>
        </a-form-model-item>
        <div style="margin-left: 11%; margin-bottom: 10px; color: #e38127">
          {{ $t('（生成支付二维码后需在该设定的时间内扫码并完成支付，否则会订单失效）') }}
        </div>
        <a-form-model-item prop="payLimit" ref="payLimit" :label="$t('信用卡支付')">
          <a-select v-model="dataForm.payLimit">
            <a-select-option value="Y">{{ $t('允许') }}</a-select-option>
            <a-select-option value="N">{{ $t('拒绝') }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item prop="certAddress" ref="certAddress" :label="$t('证书名称')">
          <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload" accept=".p12">
            <a-button v-if="fileList.length == 0"> <a-icon type="upload" /> {{ $t('上传证书') }} </a-button>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
    </div>
  </j-modal>
</template>

<script>
import { httpAction, postAction, getAction } from '@/api/manage'
export default {
  name: 'WeChatModal',
  components: {},
  data() {
    return {
      model: {},
      title: '',
      visible: false,
      confirmLoading: false,
      dataForm: {
        appid: '',
        merchants: '',
        apikey: '',
        payValidity: '10',
        payLimit: 'Y',
        certAddress: '',
      },
      labelCol: {
        xs: { span: 20 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 17 },
      },
      rules: {
        appid: [{ required: true, message: this.$t('请输入AppId') }],
        merchants: [{ required: true, message: this.$t('请输入商户号') }],
        apikey: [{ required: true, message: this.$t('请输入ApiKey') }],
        payValidity: [{ required: true, message: this.$t('请输入有效期') }],
      },
      fileList: [],
      uploading: false,
      uploadState: false,

      wechatList: [],
      rowState: '',
      url: {
        add: '/pay/bisPayChannelWechat/add',
        edit: '/pay/bisPayChannelWechat/edit',
      },
    }
  },
  mounted() {},
  methods: {
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file]
      this.uploadState = true
      return false
    },
    edit() {
      let that = this
      that.fileList = []
      that.visible = true
      getAction('/pay/bisPayChannelWechat/list').then((res) => {
        if (res.success) {
          if (res.result.records.length != 0) {
            that.dataForm = Object.assign({}, res.result.records[0])
          } else {
            that.dataForm = {
              appid: '',
              merchants: '',
              apikey: '',
              payValidity: '10',
              payLimit: 'Y',
              certAddress: '',
            }
          }
          if (that.dataForm.certAddress) {
            that.fileList.push({
              uid: new Date().getTime(),
              name: that.dataForm.certAddress,
            })
          }
        }
      })
    },
    handleOk() {
      let that = this
      if (that.uploadState) {
        that.importData()
      } else {
        that.$refs.form.validate((valid) => {
          if (valid) {
            that.confirmLoading = true
            let url = ''
            let method = ''
            if (that.dataForm.id) {
              url = that.url.edit
              method = 'put'
            } else {
              url = that.url.add
              method = 'post'
            }
            httpAction(url, that.dataForm, method)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.close()
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          }
        })
      }
    },
    importData() {
      let that = this
      let file = that.fileList[0]
      var formData = new FormData()
      formData.append('file', file)
      postAction('/sys/common/uploadLocal', formData).then((resp) => {
        if (resp.success) {
          that.dataForm.certAddress = resp.message
          that.$refs.form.validate((valid) => {
            if (valid) {
              let urls = ''
              let methods = ''
              if (that.dataForm.id) {
                urls = that.url.edit
                methods = 'put'
              } else {
                urls = that.url.add
                methods = 'post'
              }
              httpAction(urls, that.dataForm, methods).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.uploadState = false
                  that.close()
                } else {
                  that.$message.warning(res.message)
                }
              })
            }
          })
        } else {
          that.$message.error(resp.message)
        }
      })
    },
    close() {
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
  },
}
</script>
<style scoped>
.bold-font {
  font-weight: bold;
}
</style>